<template>
  <el-card class="submit-review-card">
    <div class="rating-section">
      <el-form-item 
        label="评分" 
        :rules="[{ required: true, message: '评分为必填项', trigger: 'change' }]"
        prop="userRating">
        <el-rate v-model="userRating" />
      </el-form-item>
    </div>
    <el-form :model="form" :rules="rules" ref="reviewForm" @submit.native.prevent="submitReview">
      <el-form-item label="评论" prop="comment">
        <el-input
          type="textarea"
          v-model="form.comment"
          placeholder="请在此处填写您的评论..."
          :rows="4"
          maxlength="500"
          show-word-limit
        />
      </el-form-item>
      <el-form-item label="上传图片">
        <input type="file" @change="handleImageUpload" accept="image/*" />
        <div class="uploaded-images" v-if="form.images.length">
          <div class="image-container" v-for="(image, index) in form.images" :key="index">
            <el-image
              :src="image"
              style="width: 100px; height: 100px; object-fit: cover;"
              fit="cover"
            />
            <el-button
              class="delete-button"
              icon="el-icon-close"
              circle
              size="small"
              @click="removeImage(index)"
            ></el-button>
          </div>
        </div>
      </el-form-item>
      <el-form-item>
        <el-button :loading="isSubmitting" type="primary" @click="submitReview">提交评论</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script setup lang="ts">
import { ref,defineProps } from 'vue';
import { ElCard, ElForm, ElFormItem, ElInput, ElButton, ElRate, ElImage, ElMessage, ElLoading } from 'element-plus';
import axios from 'axios';
import { useUserStore } from '@/stores/user';

const props = defineProps({
  restaurantId: String,
});
const userStore = useUserStore();

interface ReviewForm {
  comment: string;
  images: string[];
}

const userRating = ref(0);
const form = ref<ReviewForm>({
  comment: '',
  images: []
});

const rules = {
  comment: [
    { required: true, message: '评论内容不能为空', trigger: 'blur' },
    { min: 5, message: '评论内容至少需要 5 个字符', trigger: 'blur' },
  ],
  userRating: [
    { required: true, message: '评分为必填项', trigger: 'change' },
  ],
};

const reviewForm = ref();
const isSubmitting = ref(false);

const handleImageUpload = async (event: Event) => {
  const input = event.target as HTMLInputElement;
  if (input.files && input.files[0]) {
    const file = input.files[0];

    const isImage = file.type.startsWith('image/');
    const isLt2M = file.size / 1024 / 1024 < 2; // 限制图片大小为2MB

    if (!isImage) {
      ElMessage.error('只允许上传图片文件。');
      return;
    }

    if (!isLt2M) {
      ElMessage.error('图片大小不能超过 2MB。');
      return;
    }

    const formData = new FormData();
    formData.append('file', file);

    try {
      const loadingInstance = ElLoading.service({ text: '图片上传中...' });
      const response = await axios.post(`/file/upload/file`, formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
        },
      });
      loadingInstance.close();

      form.value.images.push(response.data.path);
      ElMessage.success('图片上传成功。');
    } catch (error) {
      ElMessage.error('图片上传失败，请重试。');
      console.error('Error uploading image:', error);
    }
  }
};

const removeImage = (index: number) => {
  form.value.images.splice(index, 1);
  ElMessage.info('图片已删除。');
};

const submitReview = async () => {
  reviewForm.value?.validate(async (valid: boolean) => {
    if (valid) {
      isSubmitting.value = true;
      const reviewData = {
        userId: userStore.userInfo.id,
        userRating: userRating.value,
        comment: form.value.comment,
        images: form.value.images.map((image) => ({ imageUrl: image })),
        reviewTime: new Date().toISOString(),
      };

      try {
        console.log('提交的评论数据:', reviewData);
        
        const response = await axios.post('/api/restaurants/review/'+props.restaurantId, reviewData);
        if (response.data.code !== 200) {
          ElMessage.error(response.data.message);
        } else {
          ElMessage.success('评论提交成功。');
          resetForm();
        }
      } catch (error) {
        console.error('提交评论时出错:', error);
        ElMessage.error('评论提交失败，请重试。');
      } finally {
        isSubmitting.value = false;
      }
    } else {
      ElMessage.error('请完成评论表单后再提交。');
    }
  });
};

const resetForm = () => {
  form.value.comment = '';
  form.value.images = [];
  userRating.value = 0;
};
</script>

<style scoped>
.submit-review-card {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f5f5f5;
  border-radius: 10px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

.rating-section {
  margin-bottom: 15px;
}

.uploaded-images {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.image-container {
  position: relative;
  width: 100px;
  height: 100px;
}

.delete-button {
  position: absolute;
  top: -10px;
  right: -10px;
  background: #ff4d4f;
  color: white;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}
</style>
